#include "NetWorkProDefine.h"

#include <stdio.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <sys/wait.h>



void dg_echo(int sockfd, SA* pcliaddr, socklen_t clilen)
{
    printf("sockfd :%x [%s:%d]\n",sockfd, __FILE__, __LINE__);
    int n;
    socklen_t len = clilen;
    char mesg[MAXLEN];

    while (1)
    {
        n = recvfrom(sockfd, mesg, MAXLEN - 1 , 0, pcliaddr, &len);
        display_sockaddr(pcliaddr);
        printf("client mesg :%s\n", mesg);
        //sleep(6);
        sendto(sockfd, mesg, n, 0, pcliaddr, len);      //单独响应，即单播
        //printf("server mesg:%s\n", mesg);
        memset(mesg, 0, sizeof(mesg));
    }
}

int main(int argc, char** argv)
{
    printf("welcome to UDP server![%s:%d]\n",__FILE__, __LINE__);
    int sockfd;
    struct sockaddr_in servaddr, cliaddr;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(SERV_PORT);
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if(-1 == bind(sockfd, (SA*)&servaddr, sizeof(servaddr)))
    {
        printf("bind error, code :%u\tmsg :%s\n", errno, strerror(errno));
        return 1;
    }

    dg_echo(sockfd, (SA*)&cliaddr, sizeof(cliaddr));
    return 0;
}

